package zero.jsp.tag;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;

public class Block extends BodyTagSupport {
    private String name;

    private boolean parent;

    public boolean isParent() {
        return parent;
    }

    public void setParent(boolean parent) {
        this.parent = parent;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void setPageContext(PageContext pageContext) {
        super.setPageContext(pageContext);
    }

    @Override
    public int doStartTag() throws JspException {


        return super.doStartTag();
    }

    @Override
    public int doEndTag() throws JspException {
        /*if (parent) {
            return super.doEndTag();
        }*/
        String blockName = "czyTmpl_" + name;
        ServletRequest request = pageContext.getRequest();


        if (!parent) {
            if (!StringUtils.isEmpty(bodyContent.getString())) {
                request.setAttribute(blockName, bodyContent.getString());
            }

        } else {

            //block标签中的默认值
            String defaultContent = (getBodyContent() == null) ? "" : getBodyContent().getString();
            String bodyContent = (String) request.getAttribute(blockName);
            //如果页面没有重写该模块则显示默认内容
            bodyContent = StringUtils.isEmpty(bodyContent) ? defaultContent : bodyContent;

            try {
                pageContext.getOut().write(bodyContent);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        return super.doEndTag();

    }
}
